import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useKnowledgeStore } from "@/stores/knowledge";
import { useUserStore } from "@/stores/user";
import { knowledgeApi } from "@/api/services";
import type {
  KnowledgeBase,
  KnowledgeDocument,
  CreateKnowledgeBaseRequest,
  UpdateKnowledgeBaseRequest,
  KnowledgeSearchOptions,
} from "@/types/knowledge";
import { KNOWLEDGE_TYPES, ROUTES } from "@/constants";
import { debounce } from "@/utils";

/**
 * 知识库相关的组合式函数
 */
export function useKnowledge() {
  const router = useRouter();
  const knowledgeStore = useKnowledgeStore();
  const userStore = useUserStore();

  // 响应式状态
  const isLoading = ref(false);
  const isSaving = ref(false);
  const isUploading = ref(false);
  const error = ref<string | null>(null);
  const searchQuery = ref("");
  const selectedType = ref<string | null>(null);
  const selectedTags = ref<string[]>([]);
  const sortBy = ref<string>("updatedAt");
  const sortOrder = ref<"asc" | "desc">("desc");

  // 计算属性
  const knowledgeBases = computed(() => knowledgeStore.knowledgeBases);
  const currentKnowledgeBase = computed(
    () => knowledgeStore.currentKnowledgeBase,
  );
  const documents = computed(() => knowledgeStore.documents);
  const currentDocument = computed(() => knowledgeStore.currentDocument);
  const favoriteKnowledgeBases = computed(
    () => knowledgeStore.favoriteKnowledgeBases,
  );
  const recentKnowledgeBases = computed(
    () => knowledgeStore.recentKnowledgeBases,
  );
  const myKnowledgeBases = computed(() => knowledgeStore.myKnowledgeBases);
  const hasMoreKnowledgeBases = computed(
    () => knowledgeStore.hasMoreKnowledgeBases,
  );
  const hasMoreDocuments = computed(() => knowledgeStore.hasMoreDocuments);
  const totalKnowledgeBases = computed(
    () => knowledgeStore.totalKnowledgeBases,
  );
  const totalDocuments = computed(() => knowledgeStore.totalDocuments);

  // 过滤后的知识库列表
  const filteredKnowledgeBases = computed(() => {
    let result = knowledgeBases.value;

    // 按类型过滤
    if (selectedType.value) {
      result = result.filter((kb) => kb.type === selectedType.value);
    }

    // 按标签过滤
    if (selectedTags.value.length > 0) {
      result = result.filter((kb) =>
        selectedTags.value.some((tag) => kb.tags?.includes(tag)),
      );
    }

    // 按搜索关键词过滤
    if (searchQuery.value.trim()) {
      const query = searchQuery.value.toLowerCase().trim();
      result = result.filter(
        (kb) =>
          kb.name.toLowerCase().includes(query) ||
          kb.description.toLowerCase().includes(query) ||
          kb.tags?.some((tag) => tag.toLowerCase().includes(query)),
      );
    }

    return result;
  });

  /**
   * 加载知识库列表
   */
  const loadKnowledgeBases = async (options: KnowledgeSearchOptions = {}) => {
    try {
      isLoading.value = true;
      error.value = null;

      const searchOptions = {
        page: options.page || 1,
        limit: options.limit || 20,
        query: searchQuery.value || options.query,
        type: selectedType.value || options.type,
        tags: selectedTags.value.length > 0 ? selectedTags.value : options.tags,
        sortBy: sortBy.value || options.sortBy,
        sortOrder: sortOrder.value || options.sortOrder,
        ...options,
      };

      const response =
        await knowledgeApiService.getKnowledgeBases(searchOptions);

      if (response.success) {
        if (searchOptions.page === 1) {
          knowledgeStore.setKnowledgeBases(response.data.knowledgeBases);
        } else {
          knowledgeStore.addKnowledgeBases(response.data.knowledgeBases);
        }

        knowledgeStore.setHasMoreKnowledgeBases(response.data.hasMore);
        knowledgeStore.setTotalKnowledgeBases(response.data.total);

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载知识库失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 搜索知识库（防抖）
   */
  const searchKnowledgeBases = debounce(async (query: string) => {
    searchQuery.value = query;
    await loadKnowledgeBases({ page: 1 });
  }, 300);

  /**
   * 加载知识库详情
   */
  const loadKnowledgeBase = async (knowledgeBaseId: string) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response =
        await knowledgeApiService.getKnowledgeBase(knowledgeBaseId);

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeStore.updateKnowledgeBase(knowledgeBase);
        knowledgeStore.setCurrentKnowledgeBase(knowledgeBase);

        // 添加到最近访问
        knowledgeStore.addToRecent(knowledgeBase);

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "加载知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载知识库失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 创建知识库
   */
  const createKnowledgeBase = async (data: CreateKnowledgeBaseRequest) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await knowledgeApiService.createKnowledgeBase(data);

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeStore.addKnowledgeBase(knowledgeBase);
        knowledgeStore.addToMyKnowledgeBases(knowledgeBase);

        // 跳转到知识库详情页
        await router.push(
          `${ROUTES.KNOWLEDGE_DETAIL.replace(":knowledgeId", knowledgeBase.id)}`,
        );

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "创建知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "创建知识库失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 更新知识库
   */
  const updateKnowledgeBase = async (
    knowledgeBaseId: string,
    data: UpdateKnowledgeBaseRequest,
  ) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await knowledgeApiService.updateKnowledgeBase(
        knowledgeBaseId,
        data,
      );

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeStore.updateKnowledgeBase(knowledgeBase);

        if (currentKnowledgeBase.value?.id === knowledgeBaseId) {
          knowledgeStore.setCurrentKnowledgeBase(knowledgeBase);
        }

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "更新知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新知识库失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 删除知识库
   */
  const deleteKnowledgeBase = async (knowledgeBaseId: string) => {
    try {
      const response =
        await knowledgeApiService.deleteKnowledgeBase(knowledgeBaseId);

      if (response.success) {
        knowledgeStore.removeKnowledgeBase(knowledgeBaseId);

        // 如果删除的是当前知识库，清除当前知识库
        if (currentKnowledgeBase.value?.id === knowledgeBaseId) {
          knowledgeStore.setCurrentKnowledgeBase(null);
        }

        return { success: true };
      } else {
        error.value = response.message || "删除知识库失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除知识库失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 加载文档列表
   */
  const loadDocuments = async (
    knowledgeBaseId: string,
    page: number = 1,
    limit: number = 20,
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.getDocuments(knowledgeBaseId, {
        page,
        limit,
      });

      if (response.success) {
        if (page === 1) {
          knowledgeStore.setDocuments(knowledgeBaseId, response.data.documents);
        } else {
          knowledgeStore.addDocuments(knowledgeBaseId, response.data.documents);
        }

        knowledgeStore.setHasMoreDocuments(response.data.hasMore);
        knowledgeStore.setTotalDocuments(response.data.total);

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "加载文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载文档失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载文档详情
   */
  const loadDocument = async (knowledgeBaseId: string, documentId: string) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.getDocument(
        knowledgeBaseId,
        documentId,
      );

      if (response.success) {
        const document = response.data;
        knowledgeStore.updateDocument(knowledgeBaseId, document);
        knowledgeStore.setCurrentDocument(document);

        return { success: true, data: document };
      } else {
        error.value = response.message || "加载文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "加载文档失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 创建文档
   */
  const createDocument = async (knowledgeBaseId: string, data: any) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await knowledgeApiService.createDocument(
        knowledgeBaseId,
        data,
      );

      if (response.success) {
        const document = response.data;
        knowledgeStore.addDocument(knowledgeBaseId, document);

        return { success: true, data: document };
      } else {
        error.value = response.message || "创建文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "创建文档失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 更新文档
   */
  const updateDocument = async (
    knowledgeBaseId: string,
    documentId: string,
    data: any,
  ) => {
    try {
      isSaving.value = true;
      error.value = null;

      const response = await knowledgeApiService.updateDocument(
        knowledgeBaseId,
        documentId,
        data,
      );

      if (response.success) {
        const document = response.data;
        knowledgeStore.updateDocument(knowledgeBaseId, document);

        if (currentDocument.value?.id === documentId) {
          knowledgeStore.setCurrentDocument(document);
        }

        return { success: true, data: document };
      } else {
        error.value = response.message || "更新文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "更新文档失败";
      return { success: false, message: error.value };
    } finally {
      isSaving.value = false;
    }
  };

  /**
   * 删除文档
   */
  const deleteDocument = async (
    knowledgeBaseId: string,
    documentId: string,
  ) => {
    try {
      const response = await knowledgeApiService.deleteDocument(
        knowledgeBaseId,
        documentId,
      );

      if (response.success) {
        knowledgeStore.removeDocument(knowledgeBaseId, documentId);

        // 如果删除的是当前文档，清除当前文档
        if (currentDocument.value?.id === documentId) {
          knowledgeStore.setCurrentDocument(null);
        }

        return { success: true };
      } else {
        error.value = response.message || "删除文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "删除文档失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 上传文档
   */
  const uploadDocument = async (
    knowledgeBaseId: string,
    file: File,
    options: any = {},
  ) => {
    try {
      isUploading.value = true;
      error.value = null;

      const response = await knowledgeApiService.uploadDocument(
        knowledgeBaseId,
        file,
        options,
      );

      if (response.success) {
        const document = response.data;
        knowledgeStore.addDocument(knowledgeBaseId, document);

        return { success: true, data: document };
      } else {
        error.value = response.message || "上传文档失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "上传文档失败";
      return { success: false, message: error.value };
    } finally {
      isUploading.value = false;
    }
  };

  /**
   * 批量上传文档
   */
  const batchUploadDocuments = async (
    knowledgeBaseId: string,
    files: File[],
    options: any = {},
  ) => {
    try {
      isUploading.value = true;
      error.value = null;

      const response = await knowledgeApiService.batchUploadDocuments(
        knowledgeBaseId,
        files,
        options,
      );

      if (response.success) {
        const documents = response.data.documents;
        documents.forEach((doc: KnowledgeDocument) => {
          knowledgeStore.addDocument(knowledgeBaseId, doc);
        });

        return { success: true, data: response.data };
      } else {
        error.value = response.message || "批量上传失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "批量上传失败";
      return { success: false, message: error.value };
    } finally {
      isUploading.value = false;
    }
  };

  /**
   * 搜索文档
   */
  const searchDocuments = async (
    knowledgeBaseId: string,
    query: string,
    options: any = {},
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.searchDocuments(
        knowledgeBaseId,
        { query, ...options },
      );

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "搜索失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "搜索失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 问答查询
   */
  const queryKnowledge = async (
    knowledgeBaseId: string,
    question: string,
    options: any = {},
  ) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.queryKnowledge(
        knowledgeBaseId,
        { question, ...options },
      );

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "查询失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "查询失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 收藏/取消收藏知识库
   */
  const toggleFavorite = async (knowledgeBaseId: string) => {
    try {
      const isFavorited = favoriteKnowledgeBases.value.some(
        (kb) => kb.id === knowledgeBaseId,
      );

      const response = isFavorited
        ? await knowledgeApiService.unfavoriteKnowledgeBase(knowledgeBaseId)
        : await knowledgeApiService.favoriteKnowledgeBase(knowledgeBaseId);

      if (response.success) {
        if (isFavorited) {
          knowledgeStore.removeFromFavorites(knowledgeBaseId);
        } else {
          const knowledgeBase = knowledgeBases.value.find(
            (kb) => kb.id === knowledgeBaseId,
          );
          if (knowledgeBase) {
            knowledgeStore.addToFavorites(knowledgeBase);
          }
        }

        return { success: true, isFavorited: !isFavorited };
      } else {
        error.value = response.message || "操作失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "操作失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 获取知识库统计
   */
  const getKnowledgeBaseStats = async (knowledgeBaseId: string) => {
    try {
      const response =
        await knowledgeApiService.getKnowledgeBaseStats(knowledgeBaseId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "获取统计失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "获取统计失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 导出知识库
   */
  const exportKnowledgeBase = async (
    knowledgeBaseId: string,
    format: string = "json",
  ) => {
    try {
      const response = await knowledgeApiService.exportKnowledgeBase(
        knowledgeBaseId,
        { format },
      );

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "导出失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "导出失败";
      return { success: false, message: error.value };
    }
  };

  /**
   * 导入知识库
   */
  const importKnowledgeBase = async (file: File, options: any = {}) => {
    try {
      isUploading.value = true;
      error.value = null;

      const response = await knowledgeApiService.importKnowledgeBase(
        file,
        options,
      );

      if (response.success) {
        const knowledgeBase = response.data;
        knowledgeStore.addKnowledgeBase(knowledgeBase);

        return { success: true, data: knowledgeBase };
      } else {
        error.value = response.message || "导入失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "导入失败";
      return { success: false, message: error.value };
    } finally {
      isUploading.value = false;
    }
  };

  /**
   * 重建索引
   */
  const rebuildIndex = async (knowledgeBaseId: string) => {
    try {
      isLoading.value = true;
      error.value = null;

      const response = await knowledgeApiService.rebuildIndex(knowledgeBaseId);

      if (response.success) {
        return { success: true, data: response.data };
      } else {
        error.value = response.message || "重建索引失败";
        return { success: false, message: error.value };
      }
    } catch (err: any) {
      error.value = err.message || "重建索引失败";
      return { success: false, message: error.value };
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 设置过滤条件
   */
  const setFilter = (type?: string, tags?: string[]) => {
    if (type !== undefined) selectedType.value = type;
    if (tags !== undefined) selectedTags.value = tags;
  };

  /**
   * 清除过滤条件
   */
  const clearFilters = () => {
    selectedType.value = null;
    selectedTags.value = [];
    searchQuery.value = "";
  };

  /**
   * 设置排序
   */
  const setSorting = (field: string, order: "asc" | "desc" = "desc") => {
    sortBy.value = field;
    sortOrder.value = order;
  };

  /**
   * 检查是否为收藏的知识库
   */
  const isFavorited = (knowledgeBaseId: string) => {
    return favoriteKnowledgeBases.value.some((kb) => kb.id === knowledgeBaseId);
  };

  /**
   * 检查是否为我的知识库
   */
  const isMyKnowledgeBase = (knowledgeBaseId: string) => {
    return myKnowledgeBases.value.some((kb) => kb.id === knowledgeBaseId);
  };

  // 监听搜索条件变化，自动重新加载
  watch([selectedType, selectedTags, sortBy, sortOrder], () => {
    loadKnowledgeBases({ page: 1 });
  });

  return {
    // 状态
    isLoading,
    isSaving,
    isUploading,
    error,
    searchQuery,
    selectedType,
    selectedTags,
    sortBy,
    sortOrder,
    knowledgeBases,
    currentKnowledgeBase,
    documents,
    currentDocument,
    favoriteKnowledgeBases,
    recentKnowledgeBases,
    myKnowledgeBases,
    hasMoreKnowledgeBases,
    hasMoreDocuments,
    totalKnowledgeBases,
    totalDocuments,
    filteredKnowledgeBases,

    // 方法
    loadKnowledgeBases,
    searchKnowledgeBases,
    loadKnowledgeBase,
    createKnowledgeBase,
    updateKnowledgeBase,
    deleteKnowledgeBase,
    loadDocuments,
    loadDocument,
    createDocument,
    updateDocument,
    deleteDocument,
    uploadDocument,
    batchUploadDocuments,
    searchDocuments,
    queryKnowledge,
    toggleFavorite,
    getKnowledgeBaseStats,
    exportKnowledgeBase,
    importKnowledgeBase,
    rebuildIndex,
    setFilter,
    clearFilters,
    setSorting,
    isFavorited,
    isMyKnowledgeBase,
  };
}
